using System;
using System.Collections.Generic;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;

namespace Obsady
{
    class CExcel
    {
        const string kSep = "|";

        public string getText(string aPath)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range;

            System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Globalization.CultureInfo newCI = new System.Globalization.CultureInfo("en-US");

            string str = "";
            int rCnt = 0;
            int cCnt = 0;

            System.Threading.Thread.CurrentThread.CurrentCulture = newCI;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open(aPath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;

            for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
            {
                for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
                {
                    str += (range.Cells[rCnt, cCnt] as Excel.Range).Value2 + kSep;
                }
            }

            //xlWorkBook.Close(true, null, null);
            xlApp.Quit();

            System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            return str;
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                Console.WriteLine("Unable to release the Object {0}", ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}
